#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <cstring>
#include <iostream>
#include <string>
#include "log.hpp"
#include "constants.hpp"

enum err {
    SOCKET_ERR = 1,
    CONNECT_ERR
};

void Usage(std::string cmd)
{
    std::cout << "\n\tUsage:" << cmd << " [ip]" << " [port]\n" << std::endl;
}

//./tcpClient [ip] [port]
int main(int argc, char* argv[])
{
    if(argc != 3) {
        Usage(argv[0]);
        exit(0);
    }

    signal(SIGPIPE, SIG_IGN);
    u_int16_t port = atoi(argv[2]);
    std::string ip = argv[1];

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(server);
    //短连接，短服务
    while(true)
    {
        //创建套接字
        int fd = socket(AF_INET, SOCK_STREAM, 0);
        if(fd < 0) {
            lg(FATAL, "socket err, errno:%d, errmsg:%s", errno, strerror(errno));
            errno = 0;
            exit(SOCKET_ERR);
        }
        lg(LOG, "socket success, errno:%d, errmsg:%s", errno, strerror(errno));

        bool _reconnect = false;
        int cnt = reconnect_cnt;
        do
        {
            //请求连接
            if(connect(fd, (const sockaddr*)&server, len) < 0)
            {
                lg(FATAL, "connect err, errno:%d, errmsg:%s", errno, strerror(errno));
                errno = 0;
                //exit(CONNECT_ERR);
                //重连
                _reconnect = true;
                --cnt;
                std::cerr << "connect err, reconnecting..." << cnt << std::endl;
                sleep(1);
            }
            else {
                lg(LOG, "connect success, errno:%d, errmsg:%s", errno, strerror(errno));
                break;
            }
        } while (_reconnect && cnt);
        if(cnt == 0) {
            std::cerr << "connect fail..." << std::endl;
            break;
        }
        
        //发送数据
        std::cout << "please input@ ";
        std::string msg;
        std::getline(std::cin, msg);
        ssize_t n = write(fd, msg.c_str(), msg.size());
        //接收数据
        char inbuffer[BUFFER_SIZE]; inbuffer[0] = 0;
        n = read(fd, inbuffer, sizeof(inbuffer));
        if(n < 0) {
            lg(WARNING, "read err, errno:%d, errmsg:%s", errno, strerror(errno));
            errno = 0;
        }
        else {
            std::cout << inbuffer << std::endl;
        }
        //关闭套接字
        close(fd);
    }
    return 0;
}